package cn.hchaojie.camp.week1.qa;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class Ex12ArrayMerge {
	private static final int[][][] DATA = {
			{{1, 5, 16}, {3, 4, 6, 7}},
			{{5, 6, 22, 99, 100}, {7, 8, 10, 11, 21, 23, 88}},
			{{1}, {2}},
			{{1, 3}, {2, 4}},
			{{1, 3}, {2, 4, 5}},
			{{10, 30, 40}, {2, 4, 5}},
	};
	
	private static final int[][] RESULTS = {
			{1, 3, 4, 5, 6, 7, 16},
			{5, 6, 7, 8, 10, 11, 21, 22, 23, 88, 99, 100},
			{1, 2},
			{1, 2, 3, 4},
			{1, 2, 3, 4, 5},
			{2, 4, 5, 10, 30, 40}
	};
	
	@Test
	public void verify() {
		for (int i = 0; i < DATA.length; i++) {
			int[] a1 = DATA[i][0];
			int[] a2 = DATA[i][1];
			
			int[] a3 = merge(a1, a2);
			
			assertArrayEquals(a3, RESULTS[i]);
		}
	}

	public static int[] merge(int[] a1, int[] a2) {
		int[] a3 = new int[a1.length + a2.length];

		int i = 0, j = 0, k = 0;
		
		while (i < a1.length && j < a2.length) {
			/*
			if (a1[i] < a2[j]) {
				a3[k] = a1[i++];
			} else {
				a3[k] = a2[j++];
			}
			k++;
			*/

			a3[k++] = a1[i] < a2[j] ? a1[i++] : a2[j++];
		}
		
		while (i < a1.length) {
			a3[k++] = a1[i++];
		}
		
		while (j < a2.length) {
			a3[k++] = a2[j++];
		}
		
		return a3;
	}
}
